package com.daqian.chance.example.admin.core.interceptor;

import com.daqian.chance.core.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录权限拦截器
 *
 * @author: daqian
 * @date: 2019/7/26 11:06
 */
@Component
@Slf4j
public class AuthorizeInterceptor implements HandlerInterceptor {
    /**
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    /**
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        log.debug("请求路径：{}", request.getServletPath());
        // todo xxx 待完善
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            throw UnauthorizedException.msg("未授权");
        }
        log.debug("2：{}", subject.getSession());
        log.debug("3：{}", subject.getPreviousPrincipals());
        log.debug("4：{}", subject.getPrincipal());
        log.debug("5：{}", subject.isPermitted("/sysUser"));
        return true;
    }

}
